import json
import logging

from .http_client import http_request, Method


def req(method, url, headers=None, body=None, retry=True):
    try:
        response = http_request(method=method, url=url, headers=headers, json=body)
        
        # 响应可能是dict或Response对象
        if hasattr(response, 'text'):  # 如果是Response对象
            parse_res = json.loads(response.text)
        else:  # 如果已经是dict
            parse_res = response
            
        # 判断token失效的典型错误信息
        token_error_msgs = [
            'token已过期', 'token失效', 'invalid token', 'expired token', 
            'token错误', '无效的token', 'Token expired', 'Token invalid'
        ]
        
        if "error" in parse_res:
            err_msg = str(parse_res['error'])
            # 检查是否为token相关错误且允许重试
            if retry and any(msg in err_msg for msg in token_error_msgs):
                logging.info("检测到token失效，尝试自动刷新...")
                from init import USERNAME, PASSWORD
                if USERNAME and PASSWORD:
                    from service.token_service import get_token
                    try:
                        new_token = get_token(USERNAME, PASSWORD)
                        logging.info(f"成功获取新token: {new_token[:10]}...")
                        # 更新全局HEADER和当前请求头
                        from init import HEADER
                        HEADER['Token'] = new_token
                        if headers:
                            headers['Token'] = new_token
                        else:
                            headers = HEADER.copy()
                        # 重试一次
                        return req(method, url, headers=headers, body=body, retry=False)
                    except Exception as e:
                        logging.error(f"刷新token失败: {str(e)}")
                raise Exception(f"Token失效: {err_msg}")
            raise Exception(parse_res['error'])
        return parse_res
    except json.JSONDecodeError:
        logging.error(f"响应解析失败: {response.text}")
        raise


from service.token_service import get_current_token, refresh_token
from requests.exceptions import HTTPError

def auth_request(method, url, max_retry=1, **kwargs):
    for attempt in range(max_retry + 1):
        try:
            response = http_request(
                method=method,
                url=url,
                headers={'Token': get_current_token()},
                **kwargs
            )
            if response.status_code == 401:
                raise HTTPError(response=response)
            return response.json()
        except HTTPError as e:
            if attempt == max_retry:
                raise
            refresh_token()
